package com.edu.service.impl;

import com.edu.dao.impl.UserDaoImpl;
import com.edu.entity.UserEntity;
import com.edu.service.UserService;
import com.edu.utils.JwtUtils;

import java.util.HashMap;
import java.util.Map;

public class UserServiceImpl implements UserService {
    private UserDaoImpl userDao;

    public UserServiceImpl() {
        this.userDao = new UserDaoImpl();
    }


    public boolean register(String username, String email, String password) {
        if (userDao.getUserByEmail(email) != null) {
            return false;
        }
        return userDao.createUser(username, email, password);
    }

    public Map<String, Object> login(String email, String password) {
        UserEntity user = userDao.getUserByEmailAndPassword(email, password);
        if (user != null) {
            HashMap<String, String> userMap = new HashMap<String, String>();
            userMap.put("email", user.getEmail());
            userMap.put("username", user.getUsername());
            userMap.put("role", user.getRole());
            String token = JwtUtils.generateToken(userMap);
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("userId", user.getUserId());
            resultMap.put("token", token);
            return resultMap;
        }
        return null;
    }

    @Override
    public UserEntity getUserInfoById(int userId) {
        return userDao.getUserInfoById(userId);
    }

    @Override
    public Integer updateUserInfo(String userId, String username, String newEmail, String oldPassword, String newPassword) {
        if(userDao.getUserByUserIdAndPassword(userId,oldPassword) != null) {
            return userDao.updateUserInfo(userId, username, newEmail, newPassword);
        }
        return 0;
    }

    @Override
    public Integer deleteUserInfo(String userId) {
        return userDao.deleteUserInfo(userId);
    }
}
